<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id="page-title">茉莉花收购价格</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }
        .price-board {
            margin: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .table-container {
            flex: 1;
            overflow: hidden;
            position: relative;
        }
        .table-wrapper {
            width: 100%;
            height: 100%;
            overflow: auto;
        }
        .price-table {
            border-collapse: separate;
            border-spacing: 0;
            width: auto;
        }
        .price-table th, .price-table td {
            border: 1px solid #ddd;
            padding: 6px 8px;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 0.9em;
        }
        .price-table th {
            background-color: #2c3e50;
            color: white;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        /* 第一列固定宽度 */
        .price-table th:first-child,
        .price-table td:first-child {
            position: sticky;
            left: 0;
            z-index: 5;
            width: 25px;
            min-width: 25px;
            max-width: 40px;
        }
        .price-table th:first-child {
            z-index: 20;
            background-color: #34495e;
        }
        /* 其他列统一固定宽度 */
        .price-table th:not(:first-child),
        .price-table td:not(:first-child) {
            width: 25px;
            min-width: 25px;
            max-width: 100x;
        }
        /* 统一的斑马纹效果 */
        .price-table tr:nth-child(odd):not(.special-row) td {
            background-color: #f8f9fa;
        }
        .price-table tr:nth-child(even):not(.special-row) td {
            background-color: #e9ecef;
        }
        /* 特殊行样式 */
        .price-table tr.special-row td {
            background-color: #f0f8ff;
            font-weight: bold;
        }
        .price-table tr.special-row td:first-child {
            background-color: #e6f2ff;
        }
        .price-up {
            color: #dc3545;
            font-weight: bold;
        }
        .price-down {
            color: #28a745;
            font-weight: bold;
        }
        .trend-icon {
            font-size: 0.7em;
            margin-left: 2px;
        }
        .price-value {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="price-board">
        <div class="table-container">
            <div class="table-wrapper">
                <table id="price-table" class="price-table">
                    <thead>
                        <tr>
                            <th>时间</th>
                            <!-- 市场地点列将通过JavaScript动态添加 -->
                        </tr>
                    </thead>
                    <tbody id="price-data">
                        <!-- 价格数据将通过JavaScript动态添加 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // WebSocket配置
            const WS_URL = 'wss://huajia.molihua.net/socket/';
            const REFRESH_INTERVAL = 30000;
            
            // DOM元素
            const priceTableHead = document.querySelector('#price-table thead tr');
            const priceTableBody = document.getElementById('price-data');
            const pageTitle = document.getElementById('page-title');
            
            // 应用状态
            let socket;
            let marketColumns = {};
            let priceData = {};
            let marketStats = {}; // 存储各市场的统计数据
            let refreshIntervalId;
            
            // 初始化应用
            initApplication();
            
            function initApplication() {
                updatePageTitle();
                initWebSocket();
            }
            
            function updatePageTitle() {
				const requestDate = getRequestDate(); // 使用统一的日期获取函数
				pageTitle.textContent = `${requestDate} 茉莉花收购价格`;
			}
            
            function initWebSocket() {
                try {
                    socket = new WebSocket(WS_URL);
                    
                    socket.onopen = onSocketOpen;
                    socket.onmessage = onSocketMessage;
                    socket.onclose = onSocketClose;
                    socket.onerror = onSocketError;
                } catch (error) {
                    console.error('WebSocket初始化错误:', error);
                }
            }
            
            function onSocketOpen() {
                console.log('WebSocket连接已建立');
                fetchPriceData();
                refreshIntervalId = setInterval(fetchPriceData, REFRESH_INTERVAL);
            }
            
            function onSocketMessage(event) {
                try {
                    const data = JSON.parse(event.data);
                    
                    if (data.type === 'huajia') {
                        handlePriceResponse(data);
                    }
                } catch (error) {
                    console.error('消息处理错误:', error);
                }
            }
            
            function onSocketClose(event) {
                console.log('WebSocket连接关闭:', event.code, event.reason);
                clearInterval(refreshIntervalId);
            }
            
            function onSocketError(error) {
                console.error('WebSocket错误:', error);
            }
            
            function fetchPriceData() {
                const requestDate = getRequestDate();
                const request = {
                    type: "req",
                    data: {
                        header: {
                            client_id: "",
                            token: "",
                            location: {
                                lng: 109.27227886135543,
                                lat: 22.682798781134647
                            }
                        },
                        body: {
                            type: "huajia",
                            data: requestDate
                        }
                    }
                };
                
                sendSocketRequest(request);
            }
            
            function getRequestDate() {
                const now = new Date();
                const currentHour = now.getHours();
                
                if (currentHour < 6) {
                    const yesterday = new Date(now);
                    yesterday.setDate(yesterday.getDate() - 1);
                    return formatDate(yesterday);
                }
                
                return formatDate(now);
            }
            
            function formatDate(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            }
            
            function sendSocketRequest(request) {
                if (socket && socket.readyState === WebSocket.OPEN) {
                    socket.send(JSON.stringify(request));
                } else {
                    console.warn('WebSocket未就绪，无法发送请求');
                }
            }
            
            function handlePriceResponse(response) {
                if (response.type === 'huajia' && response.data && response.data.length > 0) {
                    const marketData = response.data[0];
                    
                    if (marketData.column) {
                        updateMarketColumns(marketData.column);
                    }
                    
                    if (marketData.total) {
                        updateMarketStats(marketData.total);
                    }
                    
                    if (marketData.list && marketData.list.length > 0) {
                        updatePriceTable(marketData.list);
                    }
                }
            }
            
            function updateMarketStats(totalData) {
                marketStats = {};
                for (const [marketCode, stats] of Object.entries(totalData)) {
                    marketStats[marketCode] = {
                        opening: stats.opening_price,
                        max: stats.max_price,
                        min: stats.min_price
                    };
                }
            }
            
            function updateMarketColumns(columns) {
                marketColumns = columns;
                updateTableHeader();
            }
            
            function updateTableHeader() {
                while (priceTableHead.children.length > 1) {
                    priceTableHead.removeChild(priceTableHead.lastChild);
                }
                
                for (const [marketCode, marketName] of Object.entries(marketColumns)) {
                    const th = document.createElement('th');
                    th.textContent = marketName;
                    th.dataset.code = marketCode;
                    priceTableHead.appendChild(th);
                }
            }

            function updatePriceTable(priceList) {
                priceTableBody.innerHTML = '';
                
                // 添加特殊行
                addSpecialRow('开市', 'opening');
                addSpecialRow('最高', 'max');
                addSpecialRow('最低', 'min');
                
                // 原始数据是时间降序（新数据在前）
                priceList.forEach((currentItem, index) => {
                    const timeParts = currentItem.time.split(':');
                    const time = `${timeParts[0]}:${timeParts[1]}`;
                    const row = document.createElement('tr');
                    
                    // 时间列
                    const timeCell = document.createElement('td');
                    timeCell.textContent = time;
                    row.appendChild(timeCell);
                    
                    // 各市场价格列
                    const marketCodes = Array.from(priceTableHead.querySelectorAll('th[data-code]')).map(th => th.dataset.code);
                    
                    marketCodes.forEach(marketCode => {
                        const priceCell = document.createElement('td');
                        const currentPrice = currentItem[marketCode] !== undefined ? parseFloat(currentItem[marketCode]) : null;
                        const displayPrice = currentPrice !== null ? formatPrice(currentPrice) : '-';
                        priceCell.textContent = displayPrice;
                        
                        if (currentPrice !== null) {
                            priceCell.classList.add('price-value');
                            
                            // 正确的价格比较逻辑（降序排列时）
                            // 当前记录：priceList[index]（更新的时间点）
                            // 前一个时间点的记录：priceList[index + 1]（更早的时间点）
                            if (index < priceList.length - 1) { // 不是最后一条记录
                                const prevItem = priceList[index + 1];
                                const prevPrice = prevItem[marketCode] !== undefined ? parseFloat(prevItem[marketCode]) : null;
                                
                                if (prevPrice !== null) {
                                    if (currentPrice > prevPrice) {
                                        priceCell.classList.add('price-up');
                                        priceCell.innerHTML = `${displayPrice} <span class="trend-icon">↑</span>`;
                                    } else if (currentPrice < prevPrice) {
                                        priceCell.classList.add('price-down');
                                        priceCell.innerHTML = `${displayPrice} <span class="trend-icon">↓</span>`;
                                    }
                                }
                            }
                        }
                        
                        row.appendChild(priceCell);
                    });
                    
                    priceTableBody.appendChild(row);
                });
            }
            
            function addSpecialRow(label, statType) {
                const row = document.createElement('tr');
                row.className = 'special-row';
                
                // 标签列
                const labelCell = document.createElement('td');
                labelCell.textContent = label;
                row.appendChild(labelCell);
                
                // 各市场价格列
                const marketCodes = Array.from(priceTableHead.querySelectorAll('th[data-code]')).map(th => th.dataset.code);
                
                marketCodes.forEach(marketCode => {
                    const priceCell = document.createElement('td');
                    let price = '-';
                    
                    if (marketStats[marketCode] && marketStats[marketCode][statType]) {
                        price = formatPrice(parseFloat(marketStats[marketCode][statType]));
                    }
                    
                    priceCell.textContent = price;
                    priceCell.classList.add('price-value');
                    row.appendChild(priceCell);
                });
                
                priceTableBody.appendChild(row);
            }
            
            function formatPrice(price) {
                if (typeof price !== 'number') return price;
                
                // 保留一位小数，不四舍五入，移除多余的0
                const fixedPrice = Math.floor(price * 10) / 10;
                return fixedPrice % 1 === 0 ? fixedPrice.toString() : fixedPrice.toFixed(1).replace(/\.?0+$/, '');
            }
        });
    </script>
</body>
</html>